package com.ld.oauth2.config.oauth.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ld.common.ResultInfoFactory;
import com.ld.oauth2.config.oauth.authorize.AuthenticationSuccessListener;
import com.ld.oauth2.config.properties.SecurityProperties;
import com.ld.oauth2.emun.LoginResponseType;
import com.ld.oauth2.model.po.SysUser;
import com.ld.oauth2.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component("customAuhtenticationSuccessHandler")
@Slf4j
public class CustomAuhtenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired(required = false)//不一定要实现 有则注入容器中
    private AuthenticationSuccessListener authenticationSuccessListener;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        if(authenticationSuccessListener!=null){
            authenticationSuccessListener.successListener( httpServletRequest,  httpServletResponse,  authentication);
        }
        String pasword = httpServletRequest.getParameter(securityProperties.getPasswordParameter());
        if(LoginResponseType.JSON.equals(securityProperties.getLoginResponseType())){
            Map<String, Object> resultMap = null;
            Object principal = authentication.getPrincipal();
            if(principal !=null&&principal instanceof UserDetails){
                SysUser sysUser = (SysUser)principal;
                sysUser.setPassword(pasword);
                resultMap = getResultMap(sysUser);
               // httpServletResponse.addCookie(new Cookie("accessToken", (String) resultMap.get("access_token")));
                //httpServletResponse.addCookie(new Cookie("refreshToken", (String) resultMap.get("refresh_token")));
                resultMap.put("userInfo",JSON.toJSONString(sysUser));
//                resultMap.put("userInfo",sysUser.toString());
               //httpServletResponse.addCookie(new Cookie("userInfo", URLEncoder.encode(JSON.toJSONString(sysUser), "utf-8")));
            }
            ResultInfoFactory<Map<String, Object>> result = ResultInfoFactory.success(resultMap);
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(result.toJsonString(result));

            log.info("authentication={},", JSON.toJSONString(result));

        }else {
            log.info("authentication={},", JSON.toJSONString(authentication));
            super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
        }

    }

    private Map<String,Object> getResultMap(SysUser sysUser){
        Map<String, Object> result = new HashMap<String, Object>();
        String authenHeader = HttpUtil.getAuthenHeader();
        System.out.println(authenHeader);
        String url = "http://127.0.0.1:8000/auth/oauth/token";
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, String> reqHeader = new HashMap<String, String>();
        try {
            params.put("grant_type","password");
            params.put("username",sysUser.getUsername());
            params.put("password",sysUser.getPassword());
            reqHeader.put("Authorization",authenHeader);
            String str = HttpUtil.postUrlAsString(url, params,reqHeader);
            System.out.println(str);
            JSONObject jsonObject = JSON.parseObject(str);
            String access_token = (String) jsonObject.get("access_token");
            String token_type = (String) jsonObject.get("token_type");
            String refresh_token = (String) jsonObject.get("refresh_token");
            Integer expires_in = (Integer) jsonObject.get("expires_in");
            String scope = (String) jsonObject.get("scope");
            String jti = (String) jsonObject.get("jti");
            result.put("access_token",access_token);
            result.put("token_type",token_type);
            result.put("refresh_token",refresh_token);
            result.put("expires_in",expires_in);
            result.put("scope",scope);
            result.put("jti",jti);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
